package qrcode

import (
	"bytes"
	"encoding/json"
	"fmt"

	"gitee.com/douxuefeng/go-utils/request"
	accessToken "gitee.com/douxuefeng/go-utils/wechat/mp/accesstoken"
	"gitee.com/douxuefeng/go-utils/wechat/mp/mpconfig"
	"gitee.com/douxuefeng/go-utils/wechat/mp/params"
)

type qrcode struct {
	*mpconfig.MpConfig
}

func NewQrcode(cf *mpconfig.MpConfig) *qrcode {
	return &qrcode{cf}
}

const qrcodeUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s"

func (q *qrcode) Create(data *params.QrcodeInfo) (string, error) {
	token, err := accessToken.GetAccessToken(q.MpConfig)
	if err != nil {
		return "", err
	}
	req := request.NewRequest()
	req.SetBody(data)
	resp, err := req.Post(fmt.Sprintf(qrcodeUrl, token))
	if err != nil {
		return "", err
	}
	// fmt.Println("resp:", resp.String())
	var res params.QrcodeResp
	err = json.NewDecoder(bytes.NewReader(resp.Body())).Decode(&res)
	if err != nil {
		return "", err
	}
	if res.Ticket != "" {
		return res.Ticket, nil
	}
	return "", fmt.Errorf("获取二维码失败")
}
